import { defineStore } from "pinia";
import { getApplicationByTenant } from "/@/api/aiot/application";
import { ApplicationItem, AppTypeEnum } from "/@/api/aiot/application/models";
import { appRouteData } from "/@/router";
import authCache from "/@/utils/cache/authCache";

export const useApplicationStore = defineStore("application", {
  state: (): { applicationData: ApplicationItem[]; curAppId: string } => {
    return {
      curAppId: "",
      applicationData: [],
    };
  },
  actions: {
    /**
     * 初始化全局应用数据
     * @returns 应用列表
     */
    async initApplicationData(tenantId?: string | null) {
      if (!tenantId) {
        tenantId = authCache.getTenant();
        if (!tenantId) {
          return [];
        }
        tenantId = window.atob(tenantId);
      }
      let data: ApplicationItem[] | null = null;
      try {
        data = await getApplicationByTenant(
          {
            tenantId,
            appType: AppTypeEnum.PC,
          },
          {
            useGlobalLoading: false,
            useDefaultErrHandle: false,
            useDefaultFailHandle: false,
          }
        );
      } catch (err) {
        return null;
      }
      const enableAppData: ApplicationItem[] = [];
      if (data && data.length > 0) {
        data.forEach((el) => {
          //以应用编码作为应用根路由的名称和路由
          el.applicationCode = el.applicationCode?.toLowerCase();
        });
        //过滤未开发的应用
        appRouteData.forEach((appRoute) => {
          const el = (data as ApplicationItem[]).find((el) => el.applicationCode === appRoute.name);
          if (el) {
            enableAppData.push(el);
          }
        });
      }
      //默认选第一个应用
      if (enableAppData.length > 0) {
        this.curAppId = enableAppData[0].applicationId as string;
      } else {
        this.curAppId = "";
      }
      this.applicationData = enableAppData;
      return enableAppData;
    },
  },
});
